package com.sample.springbatch.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 放款等待发送队列redis实现类
 */
@Service
public class RedisService {


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    /**
     * 放款信息放入队列
     *
     * @param object
     * @return
     * @throws Exception
     */
    public void pushOne(Object object, String key) throws Exception {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String objStr = mapper.writeValueAsString(object);
            System.out.println("===="+objStr);
            stringRedisTemplate.opsForList().leftPush(key, objStr);

        } catch (Exception e) {
            throw new Exception(e);
        }
    }


    /**
     * 获取放款信息
     *
     * @param key 队列key
     * @return
     * @throws Exception
     */
    public synchronized Object popOne(String key, Class clazz) throws Exception {
        try {
            String objStr = stringRedisTemplate.opsForList().rightPop(key);
            if(!StringUtils.isEmpty(objStr)){
                ObjectMapper mapper = new ObjectMapper();
                return mapper.readValue(objStr, clazz);
            }else{
                return null;
            }

        } catch (Exception e) {
            throw new Exception(e);
        }
    }
}
